package com.twh.www.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.twh.www.entity.WnCart;
import com.twh.www.entity.WnGoods;
import com.twh.www.entity.WnOrder;
import com.twh.www.service.*;
import com.twh.www.mapper.WnOrderMapper;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;


@Service
public class WnOrderServiceImpl extends ServiceImpl<WnOrderMapper, WnOrder>
    implements WnOrderService{

    @Autowired
    private WnGoodsService goodsService;
    @Autowired
    private WnCartService cartService;
    @Autowired
    private AlipayService alipayService;

    @Transactional
    @Override
    public String payOrder(Integer userId, String orderId, HttpSession session) {
        List<WnCart> cartItems = cartService.getCartByUserId(userId);
        if (cartItems == null || cartItems.isEmpty()){
            return null;};
        //2.判断库存
        for(WnCart item : cartItems){
            System.out.println(1);
            //判断库存
            WnGoods good = goodsService.getById(item.getGoodsId());
            if(item.getNum() > good.getStock()){
                return  "fail:stock";
            }
        }
        //获取支付金额
        BigDecimal totalMoney = cartService.getCartTotalPrice(userId);
        //接入支付宝：
        String form = alipayService.createPayment(orderId, ""+totalMoney, "支付订单号:"+orderId);
        //保存订单id
        session.setAttribute("orderId",orderId);
        return form;
    }

    @Override
    public void orderSuccess(String orderId, Integer userId) {
//        System.out.println("123");
//        System.out.println("1: " + orderId + ", 1: " + userId);
        WnOrder order = this.lambdaQuery()
                .eq(WnOrder::getNo, orderId) // 指定查询条件：no 字段等于 orderNo
                .one();
//        System.out.println(order);
        if (order.getNo().equals(orderId) && userId!=null) {
//            System.out.println("5555");
            order.setStatus("2"); // 设置订单状态为“已支付”
            order.setPayTime(LocalDateTime.now()); // 设置支付时间
            this.updateById(order); // 更新订单
        }
    }

}




